//
//  RCProgressView.m
//  XCMao
//
//  Created by WuQingMing on 16/4/25.
//  Copyright © 2016年 xinying. All rights reserved.
//

#import "RCProgressView.h"
#define RGB(r,g,b,a)                [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]

@implementation RCProgressView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.progressBarColor = RGB(0, 173, 242, 1);
        self.progressBgColor = [UIColor colorWithWhite:0.9 alpha:1];
    }
    return self;
}

- (void)setProgress:(CGFloat)progress {
    _progress = progress;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self drawProgressBackground:context inRect:rect];
    
    if (self.progress > 0) {
        [self drawProgress:context withFrame: rect];
    }
}

- (void)drawProgressBackground:(CGContextRef)context inRect:(CGRect)rect {
    CGContextSaveGState(context);
    UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:rect.size.height/2];
    CGContextSetFillColorWithColor(context, self.progressBgColor.CGColor);
    [roundedRect fill];
    
    UIBezierPath *roundedClipPath = [UIBezierPath bezierPathWithRect:rect];
    [roundedClipPath appendPath:roundedRect];
    [roundedRect addClip];
}

- (void)drawProgress:(CGContextRef)context withFrame:(CGRect)frame {
    
    CGRect drawRect = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width * self.progress, frame.size.height);
    UIView *view = [[UIView alloc]initWithFrame:drawRect];
    view.backgroundColor = self.progressBarColor;
    view.layer.cornerRadius = drawRect.size.height/2;
//    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
//    gradientLayer.colors = @[(__bridge id)RGB(36, 213, 240, 1).CGColor,(__bridge id)RGB(15, 196, 242, 1).CGColor,(__bridge id)RGB(0, 176, 239, 1).CGColor];
//    gradientLayer.locations = @[@0.1, @0.6, @1.0];
//    gradientLayer.startPoint = CGPointMake(0, 0);
//    gradientLayer.endPoint = CGPointMake(1.0, 0);
//    gradientLayer.frame = drawRect;
//    gradientLayer.cornerRadius = drawRect.size.height/2;
//    [view.layer addSublayer:gradientLayer];
    [self addSubview:view];

}

@end
